//getJsApiData.js
'use strict';
const fs = require('fs');
const request = require('request');
const qs = require('querystring');
var cache = require('memory-cache');

//获取token
const getAccessToken = function () {
    let queryParams = {
        'grant_type': 'client_credential',
        'appid': 'xxx',
        'secret': 'xxx'
    };

    //测试 token链接
    let wxGetAccessTokenBaseUrl = 'https://api.weixin.qq.com/cgi-bin/token?'+qs.stringify(queryParams)
    console.log(wxGetAccessTokenBaseUrl)
    let options = {
        method: 'GET',
        url: wxGetAccessTokenBaseUrl
    };
    return new Promise(function(resolve, reject) {
        request(options, function (err, res, body) {
            if (res) {
                resolve(JSON.parse(body));
            } else {
                reject(err);
            }
        });
    })
};

//保存与更新
const saveToken = function () {
    getAccessToken().then(function(res) {
        var token = res['access_token'];
        fs.writeFile('./token', token, function (err) {
            console.log('token 存储完毕')
        });
        getJsApiTicket(token).then(function (data)  {
            var ticket = JSON.parse(data).ticket;
            // console.log(data.ticket)
            fs.writeFile('./ticket', ticket, function (err) {
                console.log('ticket 存储完毕')
            });
        })

    })
};

function getJsApiTicket(token) {

    // console.log('2. token ' + token);
    var reqUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + token + '&type=jsapi';

    let options = {
        method: 'get',
        url: reqUrl
    };

    return new Promise( function(resolve, reject)  {
        request(options, function (err, res, body) {
            if (res) {
                resolve(body);

            } else {
                reject(err);
            }
        })
    })
}

var timer;
const refreshToken = function () {
    saveToken();
    clearInterval(timer)
    timer = setInterval(function () {
        saveToken();
    }, 7190*1000);
};

module.exports = refreshToken;